package com.game.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.game.server.pojo.Player;
import com.yongboy.socketio.server.IOHandlerAbs;
import com.yongboy.socketio.server.transport.GenericIO;
import com.yongboy.socketio.server.transport.IOClient;

public class GameHandler extends IOHandlerAbs {

	private Map<String, Player> playerMap = new ConcurrentHashMap<String, Player>();
	private Logger log = Logger.getLogger(this.getClass());
	
	@Override
	public void OnConnect(IOClient arg0) {
		log.debug("新用户连接：" + arg0.getSessionID());
	}

	@Override
	public void OnDisconnect(IOClient client) {
		log.debug("用户断开：" + client.getSessionID());
		GenericIO genericIO = (GenericIO) client;
		Object nickNameObj = genericIO.attr.get("name");
		String name = nickNameObj.toString();
		
		emit("left", playerMap.get(name));
		playerMap.remove(name);
	}

	@Override
	public void OnMessage(IOClient client, String oriMessage) {
		log.debug("Got a message :: " + oriMessage
				+ " :: echoing it back to :: " + client.getSessionID());
		String jsonString = oriMessage.substring(oriMessage.indexOf('{'));
		jsonString = jsonString.replaceAll("\\\\", "");

		log.debug("jsonString " + jsonString);

		JSONObject jsonObject = JSON.parseObject(jsonString);
		String eventName = jsonObject.get("name").toString();
		JSONArray argsArray = jsonObject.getJSONArray("args");

		//移动
		if(eventName.equals("move")){
			GenericIO genericIO = (GenericIO) client;
			Object nickNameObj = genericIO.attr.get("name");
			if(nickNameObj == null)
				return ;
			String name = nickNameObj.toString();
			
			Player player = playerMap.get(name);
			
			player.ox = playerMap.get(name).x;
			player.oy = playerMap.get(name).y;
			
			player.color = playerMap.get(name).color;
			
			player.x = Integer.parseInt(argsArray.getString(0));
			player.y = Integer.parseInt(argsArray.getString(1));
			
			emit("move", player);
		//新用户
		}else if(eventName.equals("name")){
			String name = argsArray.getString(0);
			String color = argsArray.getString(1);
			playerMap.put(name, new Player(name, 1, 1, color));

			GenericIO genericIO = (GenericIO) client;
			genericIO.attr.put("name", name);
			
			Player[] players = new Player[playerMap.size()];
			int i = 0;
			for(String key : playerMap.keySet()){
				players[i] = playerMap.get(key);
				i++;
			}
			System.out.println("当前在线" + players.length + "人");
			emit("new", players);
		}
	}

	@Override
	public void OnShutdown() {
		System.out.println("shutdown now ~~~");
	}
	
	/**
	 * 处理用户名的通知
	 * 
	 * @author yongboy
	 * @time 2012-3-31
	 * 
	 * @param client
	 * @param oriMessage
	 * @param obj
	 */
	private void handleAckNoticName(IOClient client, String oriMessage,
			Object obj) {
		// 处理带有 消息id+ 的情况
		boolean aplus = oriMessage.matches("\\d:\\d{1,}\\+::.*?");
		if (aplus) {
			String aPlusStr = oriMessage.substring(2,
					oriMessage.indexOf('+') + 1);
			// 通知ioclient发送此消息
			ackNotify(client, aPlusStr, obj);
		}
	}
	
	private void emit(String eventName, Player[] nicknames) {
		String content = String.format("5:::{\"name\":\"%s\",\"args\":[%s]}",
				eventName, JSON.toJSONString(nicknames));
		super.broadcast(content);
	}
	
	private void emit(String eventName, Player nicknames) {
		String content = String.format("5:::{\"name\":\"%s\",\"args\":[%s]}",
				eventName, JSON.toJSONString(nicknames));
		super.broadcast(content);
	}
	
	private void emit(String eventName, String message) {
		String content = String.format(
				"5:::{\"name\":\"%s\",\"args\":[\"%s\"]}", eventName, message);
		super.broadcast(content);
	}

	private void emit(IOClient client, String eventName, String message,
			String message2) {
		String content = String.format(
				"5:::{\"name\":\"%s\",\"args\":[\"%s\",\"%s\"]}", eventName,
				message, message2);
		super.broadcast(client, content);
	}

}
